package com.itheima.health.controller;

import com.google.gson.Gson;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据报告控制器
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @DubboReference
    private MemberService memberService;

    @DubboReference
    private OrderService orderService;


    @DubboReference
    private ReportService reportService;
    /**
     * 查询用户报告
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){

        List<String> months = new ArrayList<>();
        List<Integer> memeberCount = null;
        //构造months
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,-12);
        DateFormat df = new SimpleDateFormat("yyyy.MM");
        for (int i = 0; i <12 ; i++) {
            months.add(df.format(cal.getTime()));
            cal.add(Calendar.MONTH,1);
        }

        //构造memberCount
        memeberCount = memberService.countByMonth(months);

        Map<String,Object> map = new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memeberCount);
        return  new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }



    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){

//        List<Map<String,Object>> setmealCount = Arrays.asList(
//                    new HashMap<String,Object>(){{put("name","套餐1");put("value",10);}},
//                    new HashMap<String,Object>(){{put("name","套餐2");put("value",10);}},
//                   new HashMap<String,Object>(){{put("name","套餐3");put("value",10);}}
//        );
        List<Map<String,Object>> setmealCount = orderService.countBySetmeal();


//        List<String> setmealNames = new ArrayList<>();
//        for (Map<String, Object> map : setmealCount) {
//            setmealNames.add(String.valueOf(map.get("name")));
//        }
        List<String> setmealNames = setmealCount.stream().map(e -> (String) e.get("name")).collect(Collectors.toList());

        // 构造返回结构
        Map<String,Object> map = new HashMap<>();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);

        return  new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }


    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportDate(){
        Map<String ,Object> map = reportService.getBusinessReprotData();
        return  new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS,map);
    }


    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response){

        // 获取数据
        Map<String, Object> reportData = reportService.getBusinessReprotData();
        log.debug("[导出运营数据报表]rpc rsp:{}", reportData);

        // 取出返回结果
        String reportDate = (String) reportData.get("reportDate");
        // 获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Long totalMember = (Long) reportData.get("totalMember");
        // 获取预约相关数据
        Long todayOrderNumber = (Long) reportData.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) reportData.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) reportData.get("thisMonthOrderNumber");
        // 获取到诊相关数据
        Long todayVisitsNumber = (Long) reportData.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) reportData.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) reportData.get("thisMonthVisitsNumber");
        // 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");


        try(InputStream is = ReportController.class.getClassLoader().getResourceAsStream("report_template.xlsx");
            ServletOutputStream os = response.getOutputStream();
            ) {
            // 构建excel（包含运营数据）
            Workbook workbook = new XSSFWorkbook(is);

            // 填入数据
            Sheet sheet = workbook.getSheetAt(0);
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            // 会员数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约数据
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            // 热门套餐
            int rowNum = 12;
            for (Map map : hotSetmeal) {
                // 填入数据
                sheet.getRow(rowNum).getCell(4).setCellValue((String) map.get("name"));//套餐名称
                sheet.getRow(rowNum).getCell(5).setCellValue((Long)map.get("setmeal_count"));//预约数量
                sheet.getRow(rowNum).getCell(6).setCellValue(((BigDecimal)map.get("proportion")).doubleValue());//套餐占比
                // 行号+1
                rowNum++;
            }

            // 指定数据类型
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;fileName=report_"+reportDate+".xlsx");
            // 下载
            workbook.write(os);
            // 清空缓冲区
            os.flush();

        } catch (IOException e) {
           log.error("",e);
           return new Result(false,MessageConst.GET_BUSINESS_REPORT_FAIL);
        }


        return  new Result(true,MessageConst.GET_BUSINESS_REPORT_SUCCESS);
    }

}
